package com.yr.visa.util;

import java.io.IOException;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



import com.gargoylesoftware.htmlunit.javascript.host.file.File;
import com.google.common.collect.Lists;

public abstract class ClassPathReader {
	private static Logger logger = LoggerFactory.getLogger(ClassPathReader.class);
	public static String DEFAULT_ENCODING="UTF-8";
	
	public static String readFromPath(String classpathUrl,String encode,boolean isThrows){
		
		if(StringUtils.isBlank(classpathUrl)){
			return null;
		}
	
		try {
			encode=encode==null?DEFAULT_ENCODING:encode;
			return IOUtils.toString(ClassPathReader.class.getClassLoader().getResourceAsStream(classpathUrl),encode);
		} catch (IOException e) {
			logger.error("read error from path,"+classpathUrl,e);
			if(isThrows){
				throw new RuntimeException(e);
			}
		}
		return null;
	}
	public static String readFromPathByFile(java.io.File f,String encode,boolean isThrows){
		
		if(f==null || !f.exists() ){
			if(isThrows){
				throw new RuntimeException("f is not exists");
			}else{
				return null;
			}
		}
	
		try {
			encode=encode==null?DEFAULT_ENCODING:encode;
			return FileUtils.readFileToString(f, encode);
		} catch (IOException e) {
			logger.error("read error from path,"+f,e);
			if(isThrows){
				throw new RuntimeException(e);
			}
		}
		return null;
	}
	public static List<java.io.File> readFiles(String classpathDir){
		java.io.File f  =new java.io.File(ClassPathReader.class.getClassLoader().getResource(classpathDir).getFile());
		if(f.exists() && f.isDirectory()){
			return Lists.newArrayList(f.listFiles());
		}
		return null;
	}
	 public static String getFileNameNoEx(java.io.File f) { 
		 String filename=f.getName();
	        if ((filename != null) && (filename.length() > 0)) { 
	            int dot = filename.lastIndexOf('.'); 
	            if ((dot >-1) && (dot < (filename.length()))) { 
	                return filename.substring(0, dot); 
	            } 
	        } 
	        return filename; 
	    }
	 public static String getExtensionName(String filename) { 
	        if ((filename != null) && (filename.length() > 0)) { 
	            int dot = filename.lastIndexOf('.'); 
	            if ((dot >-1) && (dot < (filename.length() - 1))) { 
	                return filename.substring(dot + 1); 
	            } 
	        } 
	        return filename; 
	    } 
	public static void main(String[] args) {
		System.out.println(readFiles("queryTemplate/yc_baojia"));
	}
}
